"""
###### 对比度拉伸
"""
# import cv2
# import numpy as np
#
# # 读取图像
# image = cv2.imread('tk.jpeg', cv2.IMREAD_GRAYSCALE)
# if image is None:
#     print("Error: Unable to load image.")
#     exit()
#
# # 获取图像的最小值和最大值
# min_val = np.min(image)
# max_val = np.max(image)
#
# # 对比度拉伸公式：s = (r - min_val) * (255 / (max_val - min_val))
# stretched_image = cv2.convertScaleAbs(image, alpha=255.0 / (max_val - min_val), beta=-min_val * 255.0 / (max_val - min_val))
#
# # 显示原始图像和对比度拉伸后的图像
# cv2.imshow('Original Image', image)
# cv2.imshow('Contrast Stretched Image', stretched_image)
# cv2.waitKey(0)
# cv2.destroyAllWindows()


"""
###### 灰度级分层
"""
# 二值映射
# import cv2
# import numpy as np
#
# # 读取图像
# image = cv2.imread('tk.jpeg', cv2.IMREAD_GRAYSCALE)
# if image is None:
#     print("Error: Unable to load image.")
#     exit()
#
# # 二值映射
# threshold = 128  # 设定阈值
# binary_image = np.where(image > threshold, 255, 0).astype(np.uint8)
#
# # 显示原始图像和二值映射后的图像
# cv2.imshow('Original Image', image)
# cv2.imshow('Binary Image', binary_image)
# cv2.waitKey(0)
# cv2.destroyAllWindows()

"""
####### 区域映射
"""
# import cv2
# import numpy as np
#
# # 读取图像
# image = cv2.imread('tk.jpeg', cv2.IMREAD_GRAYSCALE)
# if image is None:
#     print("Error: Unable to load image.")
#     exit()
#
# # 区域映射
# # 将灰度值分为4个区间：0-63, 64-127, 128-191, 192-255
# layered_image = np.zeros_like(image)
# layered_image[(image >= 0) & (image <= 63)] = 0
# layered_image[(image > 63) & (image <= 127)] = 85
# layered_image[(image > 127) & (image <= 191)] = 170
# layered_image[(image > 191) & (image <= 255)] = 255
#
# # 显示原始图像和区域映射后的图像
# cv2.imshow('Original Image', image)
# cv2.imshow('Layered Image', layered_image)
# cv2.waitKey(0)
# cv2.destroyAllWindows()

"""
#### 比特平面分层
"""
import cv2
import numpy as np
import matplotlib.pyplot as plt
#
# # 读取图像并转换为灰度图像
image_path = '1.webp'
image = cv2.imread(image_path, cv2.IMREAD_GRAYSCALE)
if image is None:
    print("Error: Unable to load image.")
    exit()
#
# # 获取图像的高度和宽度
height, width = image.shape
#
# # 初始化比特平面图像数组
bit_planes = np.zeros((8, height, width), dtype=np.uint8)
#
# # 对每个像素进行比特平面分层
for i in range(8):
    bit_plane = 2 ** i  # 当前比特平面的掩码
    bit_planes[i] = cv2.bitwise_and(image, bit_plane)  # 提取当前比特平面
#
# # 显示原始图像和每个比特平面
plt.figure(figsize=(12, 8))
plt.subplot(3, 3, 1)
plt.title('Original Image')
plt.imshow(image, cmap='gray')
plt.axis('off')
#
for i in range(8):
     plt.subplot(3, 3, i + 2)
     plt.title(f'Bit Plane {i + 1}')
     plt.imshow(bit_planes[i], cmap='gray')
     plt.axis('off')

plt.tight_layout()
plt.show()